package com.kkm.service.Imp;

import com.kkm.dao.Imp.MusicDaoImp;
import com.kkm.dao.MusicDao;
import com.kkm.pojo.PageBean;
import com.kkm.pojo.Song;
import com.kkm.service.MusicService;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class MusicServiceImp implements MusicService {
    private MusicDao musicDao=new MusicDaoImp();
    @Override
    public PageBean<Song> showAllMusic(String currentPage, int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Song> pageBean=new PageBean(); //实例化pagebean对象
        int count=musicDao.checkMusicCount();        //查询记录数

        int totalPage=count%rows==0?count/rows :count/rows+1;
        if(currPage>=totalPage){
            currPage=totalPage;
            System.out.println(currPage+"UserService");
        }

        int index=(currPage-1)*rows;
        List<Song> musics=musicDao.showAllMusic(index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(count);
        pageBean.setList(musics);

        return pageBean;

    }

    @Override
    public PageBean<Song> checkMusic(Map<String, String[]> condition, String currentPage, int rows) {
        int userCount=musicDao.checkMusicCount();
        int num=0;
        Set<String> keySet=condition.keySet();
        for(String key:keySet) {
            String value = condition.get(key)[0];//获取值
            if (!"".equals(value)) {
                num++;
            }
        }

        if(num>2){
            userCount=musicDao.checkMusicNum(condition);
        }

        //System.out.println(userCount);
        if(userCount>=1){
            int currPage=Integer.parseInt(currentPage);
            PageBean<Song> pageBean=new PageBean(); //实例化pagebean对象

            int totalPage=userCount%rows==0?userCount/rows :userCount/rows+1;
            int index=(currPage-1)*rows;
            List<Song> musics=musicDao.checkMusic(condition,index,rows);

            pageBean.setRows(rows);
            pageBean.setCurrentPage(currPage);
            pageBean.setTotalPage(totalPage);
            pageBean.setTotalCount(userCount);
            pageBean.setList(musics);
            return pageBean;
        }
        return null;
    }

    @Override
    public void deleteMusic(String id) {
        musicDao.deleteMusic(Integer.parseInt(id));
    }

    @Override
    public void modifyMusic(Map<String, String[]> condition, String sid) {
        musicDao.modifyMusic(condition,Integer.parseInt(sid));
    }

    @Override
    public Song checkMusicById(String sid) {
        return musicDao.checkMusicById(Integer.parseInt(sid));
    }

    @Override
    public int addMusic(Song song) {
        return musicDao.addMusic(song);
    }
}
